package com.lxk.controller;

import com.lxk.service.ChatService;
import com.lxk.vo.ChatGeneralModel;
import com.lxk.vo.ChatShowModel;
import com.lxk.vo.PageModel;
import com.lxk.vo.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ChatController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ChatService cs;


	/**
	 * 显示未读聊天
	 * @param pageIndex
	 * @param num
	 * @param totalPages
	 * @return
	 */
	@GetMapping("/chatUnread")
	public String toChatUnread(Model model, Integer pageIndex, Integer num, Integer totalPages) {
		if (null == pageIndex) {
			pageIndex = 1;
		}
		if (null == num) {
			num = 12;
		}
		if (null == totalPages) {
			totalPages = cs.getUnreadTotalPages(num);
		}
		PageModel<ChatGeneralModel> page = cs.getUnreadChatList(pageIndex, num, totalPages);
		model.addAttribute("data", page);
		return "chatUnread";
	}


	/**
	 * 显示全部聊天
	 * @param pageIndex
	 * @param num
	 * @param totalPages
	 * @return
	 */
	@GetMapping("/chatAll")
	public String toChatAll(Model model, Integer pageIndex, Integer num, Integer totalPages) {
		if (null == pageIndex) {
			pageIndex = 1;
		}
		if (null == num) {
			num = 12;
		}
		if (null == totalPages) {
			totalPages = cs.getAllTotalPages(num);
		}
		PageModel<ChatGeneralModel> page = cs.getAllChatList(pageIndex, num, totalPages);
		model.addAttribute("data", page);
		return "chatAll";
	}



	/**
	 * 显示聊天内容
	 * @param wxUserId
	 * @param pageIndex
	 * @param num
	 * @param totalPages
	 * @return
	 */
	@GetMapping("/chat/list")
	@ResponseBody
	public Result<PageModel<ChatShowModel>> getChatList(Integer wxUserId, Integer pageIndex, Integer num, Integer totalPages) {
		if (null==num) {
			num = 10000;
		}
		if(null==totalPages) {
			totalPages = cs.getTotalPages(num, wxUserId);
		}
		if (null==pageIndex) {
			pageIndex = 1;
		}

		PageModel<ChatShowModel> model = cs.getChatList(pageIndex, num, totalPages, wxUserId);

		//将客服回复设为已读
		cs.setUserChatRead(wxUserId);
		
		return Result.success(model);
	}
	
	/**
	 * 发送聊天内容
	 * @param wxUserId
	 * @param chatText
	 * @return
	 */
	@PostMapping("/chat/send")
	@ResponseBody
	public Result<Integer> sendChat(Integer wxUserId, String chatText) {
		cs.addChat(chatText, wxUserId);
		return Result.success(1);
	}
}
